﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AppLab.Web;
using AppLab.Web.Services;

namespace AppLab.Views.MobileBasicInfo
{
    public partial class MobileBasicInfoWindow : ChildWindow
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        private FlowContext flow = new FlowContext();
        private MobileBasicInfoData mobileBasicInfoData = new MobileBasicInfoData();
        //保存终端页面传入的终端
        private MobileBasicInfoData emp = new MobileBasicInfoData();
        //区分修改(true)、添加(false)
        private bool addOrModify = false;

        public MobileBasicInfoWindow()
        {
            InitializeComponent();
            this.DataContext = mobileBasicInfoData;
            this.addOrModify = false;
            BindMobileInfo();
        }

        public MobileBasicInfoWindow(ComboBox comb)
        {
            InitializeComponent();
            this.DataContext = mobileBasicInfoData;
            this.addOrModify = false;
            //绑定品牌
            this.BindBrands(comb);
            //绑定其他列表信息
            BindMobileInfo();
        }

        public MobileBasicInfoWindow(MobileBasicInfoData e, ComboBox comb)
        {
            InitializeComponent();
            this.DataContext = mobileBasicInfoData;
            this.IsEnabled = false;
            this.addOrModify = true;
            if (e != null) this.emp = e;
            //绑定品牌
            this.BindBrands(comb);
            //绑定其他列表信息
            BindMobileInfo();
        }

        #region 页面下拉框

        private void BindBrands(ComboBox comb)
        {
            cbMbBrand.ItemsSource = comb.ItemsSource;
            cbMbBrand.DisplayMemberPath = "BrandName";

            if (addOrModify)
            {
                cbMbBrand.SelectedValuePath = "BrandId";
                cbMbBrand.SelectedValue = emp.BrandID;
            }
        }

        private void BindMobileInfo()
        {

            //Binding mobile Category
            var queryCategorys = flow.GetCategorysQuery();
            var loadCategory = flow.Load(queryCategorys);
            loadCategory.Completed += new EventHandler(loadCategory_Completed);
            //Binding mobile CPU
            var queryCPUs = flow.GetCPUsQuery();
            var loadCPU = flow.Load(queryCPUs);
            loadCPU.Completed += new EventHandler(loadCPU_Completed);
            //Binding Screensize
            var queryScreenSize = flow.GetScreenSizesQuery();
            var loadScreenSize = flow.Load(queryScreenSize);
            loadScreenSize.Completed += new EventHandler(loadScreenSize_Completed);
            //Binding Resoulution
            var queryResoulution = flow.GetResolutionsQuery();
            var loadResoulution = flow.Load(queryResoulution);
            loadResoulution.Completed += new EventHandler(loadResoulution_Completed);
            //Binding OS
            var queryOS = flow.GetOSsQuery();
            var loadOS = flow.Load(queryOS);
            loadOS.Completed += new EventHandler(loadOS_Completed);
            //Binding Platform
            var queryPlatform = flow.GetPlatformsQuery();
            var loadPlatform = flow.Load(queryPlatform);
            loadPlatform.Completed += new EventHandler(loadPlatform_Completed);
            //Binding OutwardType
            var queryOutwardType = flow.GetOutwardTypesQuery();
            var loadOutwardType = flow.Load(queryOutwardType);
            loadOutwardType.Completed += new EventHandler(loadOutwardType_Completed);

            if (addOrModify)
            {
                //Setting MobileType, InformationTime and Prince
                this.tbMbType.Text = emp.MobileType;
                this.tbMbPrince.Text = emp.Prince.ToString();
                this.dpInfoTime.Text = emp.InformationTime.HasValue ? emp.InformationTime.Value.ToString("yyyy-MM-dd") : string.Empty;
                //Setting 3G
                if (emp.Is3G == 1) this.cbMbIs3G1.IsChecked = true;
                else if (emp.Is3G == 2) this.cbMbIs3G2.IsChecked = true;
                else this.cbMbIs3G3.IsChecked = true;
                //Setting StreamMedia
                if (emp.IsStreamMedia == 1) this.cbMbStreamMedia1.IsChecked = true;
                else if (emp.IsStreamMedia == 2) this.cbMbStreamMedia2.IsChecked = true;
                else this.cbMbStreamMedia3.IsChecked = true;
                //Setting Touch
                if (emp.IsTouch == 1) this.cbMbIsTouch1.IsChecked = true;
                else if (emp.IsTouch == 2) this.cbMbIsTouch2.IsChecked = true;
                else this.cbMbIsTouch3.IsChecked = true;
            }
        }

        void loadCategory_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOpCategory = (LoadOperation)sender;
            cbMbCategory.ItemsSource = loadOpCategory.Entities;
            cbMbCategory.DisplayMemberPath = "CategoryName";
            if (addOrModify)
            {
                cbMbCategory.SelectedValuePath = "CategoryID";
                cbMbCategory.SelectedValue = emp.CategoryID;
            }
        }

        void loadCPU_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOpCPU = (LoadOperation)sender;
            cbMbCPU.ItemsSource = loadOpCPU.Entities;
            cbMbCPU.DisplayMemberPath = "CPUSize";
            if (addOrModify)
            {
                cbMbCPU.SelectedValuePath = "CPUID";
                cbMbCPU.SelectedValue = emp.CPUID;
            }
        }

        void loadScreenSize_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOpScreen = (LoadOperation)sender;
            cbMbScreenSize.ItemsSource = loadOpScreen.Entities;
            cbMbScreenSize.DisplayMemberPath = "ScreenSizeType";
            if (addOrModify)
            {
                cbMbScreenSize.SelectedValuePath = "ScreenSizeID";
                cbMbScreenSize.SelectedValue = emp.ScreenSizeID;
            }
        }

        void loadResoulution_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOpResoulution = (LoadOperation)sender;
            cbMbResolution.ItemsSource = loadOpResoulution.Entities;
            cbMbResolution.DisplayMemberPath = "ResolutionSize";
            if (addOrModify)
            {
                cbMbResolution.SelectedValuePath = "ResolutionID";
                cbMbResolution.SelectedValue = emp.ResoulutionID;
            }
        }

        void loadOS_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOpOS = (LoadOperation)sender;
            cbMbOS.ItemsSource = loadOpOS.Entities;
            cbMbOS.DisplayMemberPath = "OSName";
            if (addOrModify)
            {
                cbMbOS.SelectedValuePath = "OSID";
                cbMbOS.SelectedValue = emp.OSID;
            }
        }

        void loadPlatform_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOpPlat = (LoadOperation)sender;
            cbMbPlatform.ItemsSource = loadOpPlat.Entities;
            cbMbPlatform.DisplayMemberPath = "PlatformName";
            if (addOrModify)
            {
                cbMbPlatform.SelectedValuePath = "PlatformID";
                cbMbPlatform.SelectedValue = emp.PlatformID;
            }
        }

        void loadOutwardType_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOpOutward = (LoadOperation)sender;
            cbMbOutwardType.ItemsSource = loadOpOutward.Entities;
            cbMbOutwardType.DisplayMemberPath = "OutwardTypeName";
            if (addOrModify)
            {
                cbMbOutwardType.SelectedValuePath = "OutwardTypeID";
                cbMbOutwardType.SelectedValue = emp.OutwardTypeID;
            }
            this.IsEnabled = true;
        }
        #endregion

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (!Verification()) return;

            MobileBasicInfoData mobile = new MobileBasicInfoData();
            //公用字段
            mobile.BrandID = (this.cbMbBrand.SelectedItem as Brand).BrandId;
            mobile.MobileType = this.tbMbType.Text;
            mobile.CategoryID = (this.cbMbCategory.SelectedItem as Category).CategoryID;
            mobile.CPUID = (this.cbMbCPU.SelectedItem as CPU).CPUID;
            mobile.ScreenSizeID = (this.cbMbScreenSize.SelectedItem as ScreenSize).ScreenSizeID;
            mobile.ResoulutionID = (this.cbMbResolution.SelectedItem as Resolution).ResolutionID;
            mobile.PlatformID = (this.cbMbPlatform.SelectedItem as Platform).PlatformID;
            mobile.OSID = (this.cbMbOS.SelectedItem as OS).OSID;
            mobile.OutwardTypeID = (this.cbMbOutwardType.SelectedItem as OutwardType).OutwardTypeID;
            mobile.Is3G = (Boolean)cbMbIs3G1.IsChecked ? 1 : ((Boolean)cbMbIs3G2.IsChecked ? 2 : 3);
            mobile.IsStreamMedia = (Boolean)cbMbStreamMedia1.IsChecked ? 1 : ((Boolean)cbMbStreamMedia2.IsChecked ? 2 : 3);
            mobile.IsTouch = (Boolean)cbMbIsTouch1.IsChecked ? 1 : ((Boolean)cbMbIsTouch2.IsChecked ? 2 : 3);
            if (!String.IsNullOrEmpty(this.dpInfoTime.Text.Replace(" ", ""))) mobile.InformationTime = DateTime.Parse(this.dpInfoTime.Text);
            if (!String.IsNullOrEmpty(this.tbMbPrince.Text.Replace(" ", ""))) mobile.Prince = int.Parse(tbMbPrince.Text.Replace(" ", ""));

            if (this.addOrModify)
            {
                //修改终端
                mobile.FlowGuid = this.emp.FlowGuid;
                mobile.MobileID = this.emp.MobileID;
                mobile.UpdateUser = WebContext.Current.User.Name;
                mobile.CurrentOperation = this.flow.UpdateMobileBasicInfo(mobile, MobileBasicInfo_Completed, null);
                this.possiblyPendingOperations.Add(mobile.CurrentOperation);
            }
            else
            {
                //录入终端
                mobile.FlowGuid = Guid.NewGuid();
                mobile.CreateUser = WebContext.Current.User.Name;
                mobile.CurrentOperation = this.flow.AddMobileBasicInfo(mobile, MobileBasicInfo_Completed, null);
                this.possiblyPendingOperations.Add(mobile.CurrentOperation);
            }
            //防止用户迅速连接点击多次
            this.OKButton.IsEnabled = false;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void MobileBasicInfo_Completed(InvokeOperation<Guid> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value != Guid.Empty)
                {
                    this.DialogResult = true;
                }
                else
                {
                    ErrorWindow.CreateNew(ErrorResources.ErrorWindowGenericError);
                }
            }
        }

        #region 数据验证

        private bool Verification()
        {
            #region Login
            if (!WebContext.Current.User.IsAuthenticated)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.MustBeLoggedInString;
                return false;
            }
            #endregion

            #region Brand
            if (this.cbMbBrand.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobileBrand;
                return false;
            }
            string getBr = (this.cbMbBrand.SelectedItem as Brand).BrandNameEN;
            string getBr1 = (this.cbMbBrand.SelectedItem as Brand).BrandNameEN1;
            string getBr2 = (this.cbMbBrand.SelectedItem as Brand).BrandNameEN2;
            string inputStrT = this.tbMbType.Text.Replace(" ", "");

            if (String.IsNullOrEmpty(inputStrT))
            {
                TipsForWrongInfo.Text = PopupDialogStrings.InputMobileModel;
                return false;
            }

            if (Regex.IsMatch(inputStrT, "[\u4e00-\u9fa5]"))
            {
                TipsForWrongInfo.Text = PopupDialogStrings.MobileBrandWithChinese;
                return false;
            }

            //手机品牌有多种简称，如TCL：TCL，OT
            if (!(inputStrT.Length > 1 && inputStrT.IndexOf("-") > 0 &&
                ((inputStrT.IndexOf(getBr + "-") == 0 && inputStrT.Length > getBr.Length + 1)
                || (inputStrT.IndexOf(getBr1 + "-") == 0 && inputStrT.Length > getBr1.Length + 1)
                || (inputStrT.IndexOf(getBr2 + "-") == 0 && inputStrT.Length > getBr2.Length + 1))))
            {
                TipsForWrongInfo.Text = PopupDialogStrings.MobileBrandAndModelIsMatched;
                return false;
            }

            #endregion

            #region InfoTime
            try
            {
                if (!string.IsNullOrEmpty(this.dpInfoTime.Text))
                {
                    DateTime.Parse(this.dpInfoTime.Text);
                }
            }
            catch
            {
                TipsForWrongInfo.Text = PopupDialogStrings.DateFormatIsIncorrect;
                return false;
            }
            #endregion

            #region DropDownList
            if (this.cbMbCPU.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobileCPUSize;
                return false;
            }
            if (this.cbMbCategory.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobileCategory;
                return false;
            }
            if (this.cbMbOutwardType.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobileOutward;
                return false;
            }
            if (this.cbMbOS.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobileOS;
                return false;
            }
            if (this.cbMbScreenSize.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobileScreenSize;
                return false;
            }
            if (this.cbMbPlatform.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobilePlatform;
                return false;
            }
            if (this.cbMbResolution.SelectedItem == null)
            {
                TipsForWrongInfo.Text = PopupDialogStrings.SelectedMobileResolution;
                return false;
            }
            #endregion

            #region RadioButton
            if (!((bool)this.cbMbIs3G1.IsChecked || (bool)this.cbMbIs3G2.IsChecked || (bool)this.cbMbIs3G3.IsChecked))
            {
                TipsForWrongInfo.Text = PopupDialogStrings.MarkedMobileIsSupport3G;
                return false;
            }
            if (!((bool)this.cbMbIsTouch1.IsChecked || (bool)this.cbMbIsTouch2.IsChecked || (bool)this.cbMbIsTouch3.IsChecked))
            {
                TipsForWrongInfo.Text = PopupDialogStrings.MarkedMobileIsSupportTouch;
                return false;
            }
            if (!((bool)this.cbMbStreamMedia1.IsChecked || (bool)this.cbMbStreamMedia2.IsChecked || (bool)this.cbMbStreamMedia3.IsChecked))
            {
                TipsForWrongInfo.Text = PopupDialogStrings.MarkedMobileIsSupportStreamMedia;
                return false;
            }
            #endregion

            #region Prince

            //判断一个字符串是否是正整数型的字符串 
            if (!String.IsNullOrEmpty(this.tbMbPrince.Text.Replace(" ", "")))
            {
                if (!Regex.IsMatch(this.tbMbPrince.Text.Replace(" ", ""), "^\\d+$"))
                {
                    TipsForWrongInfo.Text = PopupDialogStrings.InputWrongMobilePrince;
                    return false;
                }
            }

            #endregion

            return true;
        }

        /// <summary>
        /// 验证新的手机型号是否存在？
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbMbType_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.addOrModify)
            {
                string inputStrT = this.tbMbType.Text.Replace(" ", "");
                //如果用户不修改品牌与型号，就不需要验证该型号是否已经存在
                if (!(this.emp.BrandID.Equals((this.cbMbBrand.SelectedItem as Brand).BrandId) && this.emp.MobileType.Equals(inputStrT, StringComparison.CurrentCultureIgnoreCase)))
                {
                    InvokeOperation<bool> iExist = flow.IExistMobileType(inputStrT);
                    iExist.Completed += new EventHandler(iExist_Completed);
                }
                else
                {
                    this.OKButton.IsEnabled = true;
                    this.TipsForWrongInfo.Text = "";
                    this.TipsForWrongInfo.Height = 0;
                }
            }
            else
            {
                InvokeOperation<bool> iExist = flow.IExistMobileType(this.tbMbType.Text.Replace(" ", ""));
                iExist.Completed += new EventHandler(iExist_Completed);
            }
        }
        void iExist_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if ((bool)invokeOp.Value)
            {
                this.OKButton.IsEnabled = false;
                TipsForWrongInfo.Text = PopupDialogStrings.MobileModelAlreadyExist;
            }
            else
            {
                this.OKButton.IsEnabled = true;
            }
        }

        /// <summary>
        /// 控制键盘：只允许输入8位正整数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbMbPrince_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key >= Key.D0 && e.Key <= Key.D9 && !((Keyboard.Modifiers & ModifierKeys.Shift) != 0))
            {
                e.Handled = false;
            }
            else if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
        #endregion

        /// <summary>
        /// 自动匹配品牌的简写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbMbBrand_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!this.addOrModify)
            {
                this.tbMbType.Text = string.Format("{0}-", (this.cbMbBrand.SelectedItem as Brand).BrandNameEN);
            }
        }

        //用户决定取消添加新的品牌
        //private void hyNewMBBrand_Click(object sender, RoutedEventArgs e)
        //{
        //    NewMobileBrandWindow preWindow = new NewMobileBrandWindow();
        //    preWindow.Show();
        //}
    }
}

